//
//  XMChatViewController.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/7/1.
//

#import "XMChatViewController.h"
#import "XMChatView.h"
#import "XMChatBaseSet.h"
#import "XMAcceptMeetView.h"
#import "XMMeetDetailViewController.h"
#import "XMMeetDetailModel.h"
#import "XMConfirmOrderViewController.h"

#import "XMNetwork+home.h"
#import "XMNetwork+mine.h"
#import <Photos/Photos.h>

@interface XMChatViewController ()<XMChatViewDelegate, V2TIMSimpleMsgListener, V2TIMAdvancedMsgListener>

@property (nonatomic, strong) XMChatView *chatView;

@end

@implementation XMChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
        
    }];
    [self creatUI];
}

- (void)creatUI {
    [self.view addSubview:self.chatView];
    [_chatView setContentWithReceiverName:_receiverName
                             senderAvatar:_senderAvatar
                           receiverAvatar:_receiverAvatar];
    if ([[XMChatBaseSet shareInstance] baseSet]) {
        XMWeakSelf;
        [[XMChatBaseSet shareInstance] loginWithUserId:_sender userSig:_userSigStr success:^{
            [[V2TIMManager sharedInstance] addAdvancedMsgListener:self];
            [[V2TIMManager sharedInstance] addSimpleMsgListener:self];
            [weakSelf getHistoryMsg];
        }];
    }
}

- (void)sendMsgWithContent:(NSString *)content
                   msgType:(V2TIMElemType)msgType {
    XMWeakSelf;
    [[XMChatBaseSet shareInstance] sendMessageWithSender:_sender
                                                receiver:_receiver
                                                 content:content
                                             messageType:msgType
                                                 success:^(V2TIMMessage * _Nonnull msg) {
        [weakSelf.chatView sendSucessWithMsgArr:@[msg]];
    }];
}

#pragma mark - Delegate
//发送消息
- (void)messageSendWithContent:(NSString *)contentStr {
    [self sendMsgWithContent:contentStr msgType:V2TIM_ELEM_TYPE_TEXT];
//    [_Network sendMessageWithSender:self.sender
//                           receiver:self.receiver
//                            message:contentStr
//                            success:^(id  _Nonnull responseObject) {
//
//    } failure:^(NSError * _Nonnull error) {
//
//    }];
}

//发送语音消息
- (void)voiceMsgSendWithPath:(NSString *)path {
    [self sendMsgWithContent:path msgType:V2TIM_ELEM_TYPE_SOUND];
}

//发送图片消息
- (void)imgMsgSendWithPath:(NSString *)path {
    [self sendMsgWithContent:path msgType:V2TIM_ELEM_TYPE_IMAGE];
}

//发送自定义消息
- (void)customMsgSend {
    if (self.orderInfoDic && self.orderInfoDic.count > 0) {
        XMWeakSelf;
        [[XMChatBaseSet shareInstance] sendCustomMsgWithDic:self.orderInfoDic
                                                     sender:self.sender
                                                   receiver:self.receiver
                                                    success:^(V2TIMMessage * _Nonnull msg) {
            [weakSelf.chatView sendSucessWithMsgArr:@[msg]];
        }];
    }
}

//领取 转卖转赠见面
- (void)getGiveMeetWithMeetInfo:(NSDictionary *)meetDic {
    XMAcceptMeetView *meetView = [[XMAcceptMeetView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreentHeight)];
    [meetView setContentWithMeetDic:meetDic];
    [[UIApplication sharedApplication].keyWindow addSubview:meetView];
    [meetView show];
    XMWeakSelf;
    __strong typeof(XMAcceptMeetView *)strongMeetView = meetView;
    meetView.meetGetBlock = ^{
        [_Network getResellDetailInfoWitContent:[meetDic safeStringForKey:@"giveInfo"]
                                        success:^(id  _Nonnull responseObject) {
            [_Network getMeetDetailWithServiceId:[responseObject[@"data"] safeStringForKey:@"serviceId"]
                                         success:^(id  _Nonnull responseObject) {
                XMMeetDetailModel *detailModel = [XMMeetDetailModel yy_modelWithJSON:responseObject[@"data"]];
                XMConfirmOrderViewController *confirmOrderVC = [[XMConfirmOrderViewController alloc] init];
                confirmOrderVC.meetDetailModelArr = @[detailModel];
                [weakSelf.navigationController pushViewController:confirmOrderVC animated:YES];
            } failure:^(NSError * _Nonnull error) {
                
            }];
        } failure:^(NSError * _Nonnull error) {

        }];
    };
    meetView.chatMeetDetailBlock = ^{
        XMMeetDetailViewController *detailVC = [[XMMeetDetailViewController alloc] init];
        detailVC.serviceId = [meetDic safeStringForKey:@"serviceId"];
        [strongMeetView disMiss];
        [weakSelf.navigationController pushViewController:detailVC animated:YES];
    };
}

//获取历史消息
- (void)getHistoryMsg {
    XMWeakSelf;
    [[XMChatBaseSet shareInstance] getHistoryMessageWithUserId:_receiver
                                                       lastMsg:nil
                                                       success:^(NSArray<V2TIMMessage *> * _Nonnull msg) {
        [weakSelf.chatView setContentWithMessageArr:msg];
        [weakSelf customMsgSend];
    }];
//    [_Network getHistoryMessageWithSender:_sender receover:_receiver lastMsgKey:@"" success:^(id  _Nonnull reponseObject) {
//
//    } failure:^(NSError * _Nonnull error) {
//
//    }];
}

- (void)onRecvNewMessage:(V2TIMMessage *)msg {
    [self.chatView sendSucessWithMsgArr:@[msg]];
}

- (void)onRecvC2CTextMessage:(NSString *)msgID
                      sender:(V2TIMUserInfo *)info
                        text:(NSString *)text {
    NSLog(@"接受消息%@-%@-%@", msgID, info.nickName, text);
}

- (void)onRecvC2CCustomMessage:(NSString *)msgID
                        sender:(V2TIMUserInfo *)info
                    customData:(NSData *)data {
    NSLog(@"接受消息%@-%@", msgID, info.nickName);
}

#pragma mark - Init
- (XMChatView *)chatView {
    if (!_chatView) {
        _chatView = [[XMChatView alloc] initWithFrame:self.view.bounds];
        _chatView.delegate = self;
    }
    return _chatView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
